<template>
  <div class="info">
    <div class="infobox">
      <input
        type="file"
        ref="avaterFile"
        style="display: none"
        @change="seletFile"
      />
      <img :src="list.avatar | imgUrl" alt="" @click="selImg" />
      <input type="text" v-model="list.nickName" />
      <button @click="save">保存</button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { get } from "../utils/request";
import { userModi } from "../services/user";
export default {
  data() {
    return {
      list: {},
    };
  },
  // 先获取原始数据
  created() {
    get("/api/v1/user/info").then((res) => {
      if (res.code === 1) {
        this.list = { ...res.data };
      } else {
        alert("服务器异常！");
      }
    });
  },
  methods: {
    save() {
      if (this.list.nickName) {
        userModi({
          nickName: this.list.nickName,
          avatar: this.list.avatar,
        }).then((res) => {
          this.$router.push({
            name: "User",
          });
        });
      }
    },
    selImg() {
      this.$refs.avaterFile.click();
    },
    seletFile() {
      console.log(this.$refs.avaterFile.files);
      // 存储文件数据
      const formData = new FormData();
      formData.append("file", this.$refs.avaterFile.files[0]);
      // 上传选中文件数据，接受服务器返回的一个地址
      axios
        .post("http://localhost:1337/api/v1/common/upload_file", formData)
        .then((res) => (this.list.avatar = res.data.data));
    },
  },
};
</script>

<style scoped>
.infobox {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  margin-top: 3rem;
  justify-content: space-around;
  align-items: center;
}
img {
  width: 40vw;
  border-radius: 50%;
  border: 1px solid black;
}
input {
  display: block;
  width: 95%;
  border: 1px solid black;
  height: 2rem;
}
button {
  width: 50%;
  height: 3rem;
  border-radius: 10px;
  background: pink;
  font-size: 1.5rem;
  text-align: center;
  line-height: 1.5rem;
}
</style>